package com.hanzidong.cms.controller;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageInfo;
import com.hanzidong.cms.entity.Article;
import com.hanzidong.cms.entity.User;
import com.hanzidong.cms.service.ArticleService;
import com.hanzidong.cms.service.UserService;

@Controller
@RequestMapping("admin")
public class AdminController {

	@Resource
	private ArticleService articleService;
	
	@Resource
	private UserService userService;
	
	/**
	 * 跳转到管理员中心页面
	 * @return
	 */
	@RequestMapping(value = {"","/","index"})
	public String index() {
		
		return "admin/index";
	}
	
	/**
	 * 后台管理员查询文章数据
	 * @param m
	 * @param status
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@RequestMapping("articles")
	public String articles(Model m,Integer status,
			@RequestParam(defaultValue = "1")Integer pageNum,
			@RequestParam(defaultValue = "3")Integer pageSize) {
		
		//封装查询条件
		Article article = new Article();
		
		//状态码2为查询全部，所以不封装查询条件
		if(status != null && status != 2) {
			article.setStatus(status);
		}
		
		
		//查询数据
		PageInfo<Article> info = articleService.list(pageNum, pageSize, article);
		
		//将数据返回给jsp
		m.addAttribute("info", info);
		m.addAttribute("status", status);
		
		return "admin/articles";
	}
	
	/**
	 * 修改文章的状态
	 * @param article
	 * @return
	 */
	@RequestMapping("updateArticle")
	@ResponseBody
	public boolean updateArticle(Article article) {
		
		return articleService.updateArticle(article);
	}
	
	/**
	 * 用户管理
	 * @param m
	 * @param user
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@RequestMapping("users")
	public String users(Model m,User user,
			@RequestParam(defaultValue = "1")Integer pageNum,
			@RequestParam(defaultValue = "3")Integer pageSize) {
		
		//如果locked的值为2，则表示要查询全部，所以将其值改为null
		if(user.getLocked() != null && user.getLocked() ==2) {
			user.setLocked(null);
		}
		
		//查询用户
		PageInfo<User> info = userService.listUsers(pageNum,pageSize,user);
		
		//将数据返回给jsp
		m.addAttribute("info", info);
		m.addAttribute("user", user);
		
		return "admin/users";
	}
	
	/**
	 * 修改用户的锁定状态
	 * @param user
	 * @return
	 */
	@RequestMapping("updateUser")
	@ResponseBody
	public boolean updateUser(User user) {
		
		return userService.updateUser(user);
	}
}
